<?php

namespace cosy\framework\middleware;

use stdClass;
use think\Response;
use think\Request;

class HandleResponseBody
{
    public function handle(Request $request, \Closure $next)
    {
        $response = $next($request);

        if ($response instanceof Response) {
            $data = $response->getData();
            $message = 'success';
            if (gettype($data) == 'string') {
                $message = $data;
                $data = new stdClass();

            }
            $response = Response::create(
                [
                    'code' => 200,
                    'message' => $message,
                    'data' => $data,
                    'success' => true
                ], 'json')
                ->code(200)
                ->header([
                    'Access-Control-Allow-Credentials' => 'true',
                    'Access-Control-Allow-Methods' => 'GET, POST, PATCH, PUT, DELETE, OPTIONS',
                    'Access-Control-Allow-Headers' => 'Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-CSRF-TOKEN, X-Requested-With,token',
                    'Access-Control-Allow-Origin' => '*',
                    'Access-Control-Max-Age' => 6000,
                ]);
        }

        return $response;
    }
}